package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.aliyuncs.exceptions.ClientException;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.*;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.service.IOrderSettingListService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.IDUtils;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = IOrderSettingListService.class)
@Transactional
public class OrderSettingListServiceImpl implements IOrderSettingListService {

    @Autowired
    private IOrderSettingListDao orderSettingListDao;

    @Autowired
    private IOrderSettingDao orderSettingDao;

    @Autowired
    private IMemberDao memberDao;

    @Autowired
    private IOrderDao orderDao;

    // 分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) throws Exception {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);
        Page<Order> page = orderSettingListDao.findPage(queryString);
        long total = page.getTotal();
        List<Order> rows = page.getResult();
        if (rows != null && rows.size() > 0){
            for (Order row : rows) {

                row.setOrderStatus("已预约");

            }
        }

        return new PageResult(total,rows);
    }

    // 添加功能
    @Override
    public Result add(@RequestBody Map map, Integer[] setmealIds) throws Exception {


        //检查用户选择日期是否进行了预约设置
        String  orderDate = (String) map.get("orderDate");
        Date date = DateUtils.parseString2Date(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        if (orderSetting == null){ // 不存在
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);

        }

        // 检查用户预约日期是否已约满
        int number = orderSetting.getNumber();
        int reservations = orderSetting.getReservations();
        if (reservations >= number){ // 预约已满
            return new Result(false, MessageConstant.ORDER_FULL);
        }

        // 检查用户是否为会员,不是会员,自动注册,再预约
        String  phoneNumber = (String) map.get("phoneNumber");
        Member member = memberDao.findByTelephone(phoneNumber);
        if (member != null){

            // 检查用户是否在同一天预约了同一个套餐
            Integer memberId = member.getId();
            for (Integer setmealId : setmealIds) {

                Order o = new Order(memberId, date, setmealId);
                List<Order> orderList = orderDao.findByCondition(o);
                if (orderList != null && orderList.size() > 0){ // 重复预约
                    return new Result(false, MessageConstant.HAS_ORDERED);
                }
            }

        }else {
            String name = (String) map.get("name");
            member = new Member();
            member.setPhoneNumber(phoneNumber);
            member.setName(name);
            String fileNumber = IDUtils.createID(orderDate.replaceAll("-", ""));
            member.setFileNumber(fileNumber);
            member.setRegTime(date);
            // 会员注册
            memberDao.add(member);

        }

        // 添加预约
        for (Integer setmealId : setmealIds) {
            Order order = new Order();
            order.setMemberId(member.getId());
            order.setOrderDate(date);
            order.setOrderType((String) map.get("orderType"));
            order.setOrderStatus(Order.ORDERSTATUS_NO);
            order.setSetmealId(setmealId);
            orderDao.add(order);

            // 5、预约成功，更新当日的已预约人数
            orderSetting.setReservations(orderSetting.getReservations()+1);
            orderSettingDao.editByOrderSetting(orderSetting);
        }

        return new Result(true,MessageConstant.ORDER_SUCCESS);
    }


    // 取消预约
    @Override
    public void cancel(Map map) throws Exception {
        Integer id = (Integer) map.get("id");
        String  telephone = (String) map.get("telephone");
        Order order = orderDao.findOrderById(id);
        // 删除订单信息
        orderDao.delete(id);

        // 5、删除成功，更新已预约人数
        Date orderDate = order.getOrderDate();
        Date date = DateUtils.parseString2Date(DateUtils.parseDate2String(orderDate));
        OrderSetting orderSetting = orderSettingDao.findByOrderDate(date);
        orderSetting.setReservations(orderSetting.getReservations()-1);
        orderSettingDao.editByOrderSetting(orderSetting);

        // 发送短信通知客户
        Integer code = ValidateCodeUtils.generateValidateCode(4);
        SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,code.toString());
    }

    // 批量取消预约
    @Override
    public void batchCancel(Integer[] orderIds) {
        for (Integer orderId : orderIds) {
            orderDao.delete(orderId);
        }
    }
}
